package com.hunit.mqtt_dome.emqx;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Description : MQTT发送客户端的回调处理类
 * @Author : Sherlock
 * @Date : 2023/8/1 16:30
 */
@Component
public class MqttSendCallBack implements MqttCallback {

    private static final Logger logger = LoggerFactory.getLogger(MqttSendCallBack.class);

    /**
     * 连接丢失后，一般在这里面进行重连
     *
     * @param cause 原因
     */
    @Override
    public void connectionLost(Throwable cause) {
        logger.info("发送端连接断开，原因：{}", cause.getMessage());
        cause.printStackTrace();
    }

    /**
     * 消息到达处理
     *
     * @param topic       主题
     * @param mqttMessage 消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        String message = new String(mqttMessage.getPayload());
        logger.info("发送端接收消息主题：{}", topic);
        logger.info("发送端接收消息Qos：{}", mqttMessage.getQos());
        logger.info("发送端接收消息内容：{}", message);
    }

    /**
     * 消息发送完成处理
     *
     * @param iMqttDeliveryToken token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("消息发送成功，deliveryToken={}", iMqttDeliveryToken.getMessageId());
    }
} 